package com.aegis.autodeployplugin.api;

import org.apache.commons.codec.binary.Base64;

import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * desc     :   Retrofit 请求工具
 *
 * @author : Aegis_Lee
 * date     : 2021/7/19
 * email    : 476810504@qq.com
 */
public class RetrofitUtil {
    private RetrofitUtil(){}

    private static class HOLDER{
        private static final RetrofitUtil INSTANCE = new RetrofitUtil();
    }

    public static RetrofitUtil getInstance(){
        return HOLDER.INSTANCE;
    }

    /**
     * 创建 Retrofit
     * @param baseUrl 请求域名
     * @return {@link Retrofit}
     */
    public Retrofit create(String baseUrl){
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        // 上传超时时间，正常不会这么久
        builder.writeTimeout(24, TimeUnit.HOURS);
        OkHttpClient okHttpClient = builder.build();
        return new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build();
    }

    /**
     * 钉钉机器人消息签名生成
     *
     * @param timestamp 当前时间戳
     * @param secret    钉钉Secret
     * @return  加密后的字符串
     */
    public String createSign(Long timestamp, String secret) {
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = null;
        try {
            mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            return URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
